package com.shisan.tingshu.user.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.shisan.tingshu.user.config.properties.WxAutoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

/**
 * 微信的自动配置类
 */
@Configuration
// 加上下面的注解后，无需在WxAutoProperties中加上@Component注解
@EnableConfigurationProperties(WxAutoProperties.class)
public class WxAppAutoConfiguration {

    @Autowired
    WxAutoProperties wxAutoProperties;

    /**
     * 定义 WxMaService 的Bean对象
     */
    @Bean
    public WxMaService wxMaService() {
        // 创建一个WxMaService接口的对象
        WxMaService wxMaService = new WxMaServiceImpl();
        // 创建一个微信配置对象
        WxMaDefaultConfigImpl wxMaDefaultConfig = new WxMaDefaultConfigImpl();
        wxMaDefaultConfig.setAppid(wxAutoProperties.getAppId());
        wxMaDefaultConfig.setSecret(wxAutoProperties.getAppSecret());
        // 将配置对象放到WxMaService接口对象中
        wxMaService.setWxMaConfig(wxMaDefaultConfig);

        return wxMaService;
    }

    /**
     * 定义 RSA 签名的Bean对象
     */
    @Bean
    public RsaSigner rsaSigner() {
        // 读取 RAS 加密证书
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        // 创建一个工厂对象。要传递的参数：1.证书的路径 2.证书的秘钥（生成证书用的是什么秘钥，下面就传入什么秘钥）
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());
        // 通过工厂对象获取钥匙对象（公钥和私钥）
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        // 获取私钥
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
        RsaSigner rsaSigner = new RsaSigner(aPrivate);

        return rsaSigner;
    }
}
